package com.example.basesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.basesystem.common.Result;
import com.example.basesystem.entity.SysMenu;
import com.example.basesystem.service.SysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 菜单控制器
 */
@Tag(name = "菜单管理", description = "菜单相关接口")
@RestController
@RequestMapping("/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 查询菜单列表
     */
    @Operation(summary = "查询菜单列表", description = "查询菜单列表接口")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<SysMenu>> list(@Parameter(description = "菜单类型") @RequestParam(required = false) Integer type) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(type != null, SysMenu::getType, type)
                .orderByAsc(SysMenu::getSort);
        List<SysMenu> menuList = sysMenuService.list(queryWrapper);
        return Result.success(menuList);
    }

    /**
     * 查询菜单树
     */
    @Operation(summary = "查询菜单树", description = "查询菜单树接口")
    @GetMapping("/tree")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<SysMenu>> tree() {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysMenu::getSort);
        List<SysMenu> menuList = sysMenuService.list(queryWrapper);
        List<SysMenu> menuTree = sysMenuService.buildMenuTree(menuList);
        return Result.success(menuTree);
    }

    /**
     * 根据ID查询菜单
     */
    @Operation(summary = "根据ID查询菜单", description = "根据ID查询菜单接口")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public Result<SysMenu> getById(@PathVariable Long id) {
        SysMenu menu = sysMenuService.getById(id);
        return Result.success(menu);
    }

    /**
     * 根据角色ID查询菜单列表
     */
    @Operation(summary = "根据角色ID查询菜单列表", description = "根据角色ID查询菜单列表接口")
    @GetMapping("/role/{roleId}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<SysMenu>> getMenusByRoleId(@PathVariable Long roleId) {
        List<SysMenu> menuList = sysMenuService.getMenusByRoleId(roleId);
        return Result.success(menuList);
    }

    /**
     * 新增菜单
     */
    @Operation(summary = "新增菜单", description = "新增菜单接口")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:menu:add')")
    public Result<Object> add(@Validated @RequestBody SysMenu menu) {
        menu.setCreateTime(LocalDateTime.now());
        menu.setStatus(1);
        menu.setIsDeleted(0);
        boolean result = sysMenuService.save(menu);
        return result ? Result.success() : Result.error("新增菜单失败");
    }

    /**
     * 修改菜单
     */
    @Operation(summary = "修改菜单", description = "修改菜单接口")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result<Object> update(@Validated @RequestBody SysMenu menu) {
        menu.setUpdateTime(LocalDateTime.now());
        boolean result = sysMenuService.updateById(menu);
        return result ? Result.success() : Result.error("修改菜单失败");
    }

    /**
     * 删除菜单
     */
    @Operation(summary = "删除菜单", description = "删除菜单接口")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result<Object> delete(@PathVariable Long id) {
        // 查询是否有子菜单
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId, id);
        long count = sysMenuService.count(queryWrapper);
        if (count > 0) {
            return Result.error("存在子菜单，不能删除");
        }
        boolean result = sysMenuService.removeById(id);
        return result ? Result.success() : Result.error("删除菜单失败");
    }
}